#!/bin/bash

#output 
#If not given in env, using default
DEFAULT_OUTPUT=/root/tarball
#rpm official package release number
declare -A PACKAGE_VERSION_MAPPING
PACKAGE_VERSION_MAPPING=(
[keystone]="8.0.0.1"
[python-keystoneclient]="1.7.2.1"
[nova]="12.0.0.1"
[python-novaclient]="2.30.1.1"
[neutron]="7.0.0.2"
[python-neutronclient]="3.1.0.1"
[cinder]="7.0.0.1"
[python-cinderclient]="1.4.0.1"
[glance]="11.0.0.1"
[python-glanceclient]="1.1.0.1"
[ceilometer]="5.0.0.1"
[python-ceilometerclient]="1.5.0.1"
[heat]="5.0.0.1"
[python-heatclient]="0.8.0.1"
[oslo.db]="2.6.0.1"
)


Usage()
{
    echo "Usage: `basename $0` [-l local source code ] [-m package release version ] [-n tag ] [-o output ] [ -r git repo ]"
    #If -l, link ./private-tarball.sh -l /root/git-repo/cinder/, then get package name cinder
    #If -r, link ./private-tarball.sh -r ssh://git@192.168.89.100:10022/openstack/cinder.git get package name cinder
    #clone package in tmp_dir, checkout tag
    exit 1
}

[ $# -eq 0 ] && Usage

while getopts 'l:m:n:o:r:' opts
do 
    case $opts in 
        l)
            PACKAGE="$(basename $OPTARG)"
            LOCAL="$(cd $(dirname $OPTARG) && pwd)/${PACKAGE}"
            ;;
        m)
            RELEASE_VERSION=${OPTARG}
            ;;
        n)
            PRIVATE_TAG=${OPTARG}
            ;;
        o)
            OUTPUT=${OPTARG}
            ;;
        r)
            PACKAGE="$(basename $OPTARG)"
            PACKAGE=${PACKAGE%.*}
            REMOTE=${OPTARG}
            ;;
        *)
            echo " Unkown opts "
            Usage
            exit 1
            ;;
    esac
done


ParseInput()
{
    if [ -z "${LOCAL}" ] && [ -z "${REMOTE}" ]; then
       echo "Not Found source code in local or remote" 
       exit 1
    fi
    if [ -z "${RELEASE_VERSION}" ] ; then 
        RELEASE_VERSION=${PACKAGE_VERSION_MAPPING["${PACKAGE}"]}
        if [ -z "${RELEASE_VERSION}" ]; then
            echo "Not Found RELEASE_VERSION in mapping"
            exit 1
        fi
    fi
    if [ -z "${PRIVATE_TAG}" ]; then
        echo "Not Found PRIVATE_TAG"
        exit 1
    fi
    if [ ! -d "${OUTPUT}" ]; then
        OUTPUT=${DEFAULT_OUTPUT}
        mkdir -p ${OUTPUT}/${PACKAGE}
    fi
}

BuildTarball()
{
    target=$1
    local tmp_dir=$(mktemp -d)
    cp ${target} ${tmp_dir}/${PACKAGE} -R
    cd ${tmp_dir}/${PACKAGE}
    git checkout ${PRIVATE_TAG}
    if [ 0 -ne $? ]; then
        echo "Invalid Tag"
        exit 1
    fi
    OSLO_PACKAGE_VERSION=${RELEASE_VERSION} python setup.py sdist
    #will be changed with rsync 
    cp ./dist/${PACKAGE}-${RELEASE_VERSION}.tar.gz ${OUTPUT}/
    rm -rf ${tmp_dir}
}

main()
{
    ParseInput
    if [ ! -z "${LOCAL}" ]; then
        BuildTarball ${LOCAL}
    elif [ ! -z "${REMOTE}" ]; then
        rm ${OUTPUT}/${PACKAGE}/ -rf
        git clone ${REMOTE} ${OUTPUT}/${PACKAGE}
        BuildTarball ${OUTPUT}/${PACKAGE}
    fi
}

main "$@"
